﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Noris.Schedule.Support;
using Noris.Schedule.Support.Core;
using Noris.Schedule.Support.Sql;
using Noris.Schedule.Support.DataFace;

namespace Noris.Schedule.Support.Forms
{
	public partial class LoginForm : Noris.Schedule.Support.Components.FormC
	{
		public LoginForm()
		{
			InitializeComponent();
			this._InitForm();
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}


		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this._LoginText = new System.Windows.Forms.TextBox();
			this._PasswText = new System.Windows.Forms.TextBox();
			this._ProfileCmb = new System.Windows.Forms.ComboBox();
			this._RunBtn = new System.Windows.Forms.Button();
			this._ExitBtn = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// _LoginText
			// 
			this._LoginText.Location = new System.Drawing.Point(381, 130);
			this._LoginText.Name = "_LoginText";
			this._LoginText.Size = new System.Drawing.Size(177, 20);
			this._LoginText.TabIndex = 2;
			// 
			// _PasswText
			// 
			this._PasswText.Location = new System.Drawing.Point(381, 158);
			this._PasswText.Name = "_PasswText";
			this._PasswText.PasswordChar = '*';
			this._PasswText.Size = new System.Drawing.Size(177, 20);
			this._PasswText.TabIndex = 3;
			// 
			// _ProfileCmb
			// 
			this._ProfileCmb.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this._ProfileCmb.FormattingEnabled = true;
			this._ProfileCmb.Location = new System.Drawing.Point(381, 184);
			this._ProfileCmb.Name = "_ProfileCmb";
			this._ProfileCmb.Size = new System.Drawing.Size(177, 21);
			this._ProfileCmb.TabIndex = 4;
			// 
			// _RunBtn
			// 
			this._RunBtn.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this._RunBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this._RunBtn.Location = new System.Drawing.Point(381, 212);
			this._RunBtn.Margin = new System.Windows.Forms.Padding(0);
			this._RunBtn.Name = "_RunBtn";
			this._RunBtn.Size = new System.Drawing.Size(85, 27);
			this._RunBtn.TabIndex = 5;
			this._RunBtn.Text = "Přihlásit";
			this._RunBtn.UseVisualStyleBackColor = true;
			this._RunBtn.Click += new System.EventHandler(this._RunBtn_Click);
			// 
			// _ExitBtn
			// 
			this._ExitBtn.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this._ExitBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
			this._ExitBtn.Location = new System.Drawing.Point(473, 212);
			this._ExitBtn.Margin = new System.Windows.Forms.Padding(0);
			this._ExitBtn.Name = "_ExitBtn";
			this._ExitBtn.Size = new System.Drawing.Size(85, 27);
			this._ExitBtn.TabIndex = 6;
			this._ExitBtn.Text = "Storno";
			this._ExitBtn.UseVisualStyleBackColor = true;
			this._ExitBtn.Click += new System.EventHandler(this._ExitBtn_Click);
			// 
			// LoginForm
			// 
			this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
			this.ClientSize = new System.Drawing.Size(595, 388);
			this.ControlBox = false;
			this.Controls.Add(this._ExitBtn);
			this.Controls.Add(this._RunBtn);
			this.Controls.Add(this._ProfileCmb);
			this.Controls.Add(this._PasswText);
			this.Controls.Add(this._LoginText);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "LoginForm";
			this.ShowIcon = false;
			this.ShowInTaskbar = true;
			this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Scheduler, login";
			this.Paint += new System.Windows.Forms.PaintEventHandler(this.LoginForm_Paint);
			this.ResumeLayout(false);
			this.PerformLayout();

		}
		#endregion

		private System.Windows.Forms.TextBox _LoginText;
		private System.Windows.Forms.TextBox _PasswText;
		private System.Windows.Forms.ComboBox _ProfileCmb;
		private System.Windows.Forms.Button _RunBtn;
		private System.Windows.Forms.Button _ExitBtn;
		private Brush _BackBrushH = null;
		private Brush _BackBrushV = null;
		private bool _BackImageExists;

		private void _InitForm()
		{
			// Průhlednost okrajů:
			this.TransparencyKey = Color.Snow;
			this.BackColor = Color.Snow;
			
			this.DialogResult = DialogResult.None;
			this.CancelButton = this._ExitBtn;
			this.AcceptButton = this._RunBtn;

			this._PrepareBackImage();
			this._ProfileCmb.DropDownHeight = 130;
			this._ProfileCmb.IntegralHeight = true;
			this._LoginText.Text = Steward.LastLogin;
			this._FillProfiles();
		}

		private void _PrepareBackImage()
		{
			string backImage = Steward.AppConfig.LoginBackImage;
			if (!String.IsNullOrEmpty(backImage) && System.IO.File.Exists(backImage))
			{
				this.BackgroundImage = Image.FromFile(backImage);
				this._BackImageExists = true;
			}
			else
			{
				this._BackImageExists = false;
			}
		}
		/// <summary>
		/// Naplní profily do comboboxu
		/// </summary>
		private void _FillProfiles()
		{
			string currentProfile = Steward.Connect.ProfileName;
			int selectItemIndex = -1;
			this._ProfileCmb.Items.Clear();
			this._ProfileCmb.Sorted = false;
			this._DbProfileList = Steward.AppConfig.DbProfileList;
			foreach (ConnectProfile dbProfile in this._DbProfileList)
			{
				string name = dbProfile.ProfileName;
				this._ProfileCmb.Items.Add(name);
				if (name == currentProfile)
					selectItemIndex = this._ProfileCmb.Items.Count - 1;
			}
			
			if (selectItemIndex < 0 && this._ProfileCmb.Items.Count > 0) selectItemIndex = 0;
			if (this._ProfileCmb.Items.Count > 0)
				this._ProfileCmb.SelectedIndex = selectItemIndex;

			// this._ProfileCmb.MaxDropDownItems = 8;
			this._ProfileCmb.DropDownHeight = 100;
			this._ProfileCmb.IntegralHeight = true;
		}
		/// <summary>
		/// Soupis profilů, které jsou načteny a zobrazeny ve formuláři.
		/// Počet a pořadí odpovídá ComboBoxu.
		/// </summary>
		private List<ConnectProfile> _DbProfileList;
		/// <summary>
		/// Vypíše texty labelů přímo metodou DrawString, abych nemusel řešit barvu pozadí labelu (Transparent) nad obrázkem.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void LoginForm_Paint(object sender, PaintEventArgs e)
		{
			// Pokud není obrázek, vykreslím pozadí ručně:
			if (!this._BackImageExists)
			{
				// Příprava nástrojů Brush pro kreslení background:
				if (this._BackBrushH == null || this._BackBrushV == null)
				{
					System.Drawing.Drawing2D.LinearGradientBrush lgbH = new System.Drawing.Drawing2D.LinearGradientBrush
						 (this.ClientRectangle, Color.ForestGreen, Color.FromArgb(13, 93, 16), 90F);
					lgbH.SetSigmaBellShape(0.33F);
					this._BackBrushH = lgbH;

					System.Drawing.Drawing2D.LinearGradientBrush lgbV = new System.Drawing.Drawing2D.LinearGradientBrush
						 (this.ClientRectangle, Color.FromArgb(64, Color.DarkGreen), Color.FromArgb(64, Color.Green), 00F);
					lgbV.SetSigmaBellShape(0.67F);
					this._BackBrushV = lgbV;
				}

				using (Brush back = new SolidBrush(this.TransparencyKey))
				{
					e.Graphics.FillRectangle(back, this.ClientRectangle);
				}

				// Kreslení background:
				Rectangle area = this.ClientRectangle;
				int skewX = 16;
				int skewY = 8;
				Point[] shape = new Point[]{
					new Point(area.X + skewX, area.Y),
					new Point(area.Right - skewX, area.Y),
					new Point(area.Right, area.Y + skewY),
					new Point(area.Right, area.Bottom - skewY),
					new Point(area.Right - skewX, area.Bottom),
					new Point(area.X + skewX, area.Bottom),
					new Point(area.X, area.Bottom - skewY),
					new Point(area.X, area.Y + skewY),
					new Point(area.X + skewX, area.Y) };
				e.Graphics.FillPolygon(this._BackBrushH, shape);
				// e.Graphics.FillRectangle(this._BackBrushH, this.ClientRectangle);
				// e.Graphics.FillRectangle(this._BackBrushV, this.ClientRectangle);

				// Titulek "Helios Green" / "Plánovací tabule":
				var graphState = e.Graphics.Save();
				e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
				e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

				using (Brush textBrush = new SolidBrush(Color.Ivory))
				using (Font textFontBig = new Font(FontFamily.GenericSansSerif, 20F, FontStyle.Bold))
				using (Font textFontMid = new Font(FontFamily.GenericSansSerif, 12F, FontStyle.Bold))
				{
					e.Graphics.DrawString("Helios Green", textFontBig, textBrush, 30F, 100F);
					e.Graphics.DrawString("Plánovací tabule", textFontMid, textBrush, 30F, 140F);
				}
				e.Graphics.Restore(graphState);
			}

			// Texty "Login", "Heslo", "Databáze":
			using (Font font = new Font(this._RunBtn.Font, FontStyle.Bold))
			using (Brush brush = new SolidBrush(Color.FromArgb(252, 254, 252)))
			{
				e.Graphics.DrawString("Login", font, brush, new PointF(305, 133));
				e.Graphics.DrawString("Heslo", font, brush, new PointF(305, 161));
				e.Graphics.DrawString("Databáze", font, brush, new PointF(305, 189));
			}
		}
		/// <summary>
		/// Přihlásit button click
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void _RunBtn_Click(object sender, EventArgs e)
		{
			int profileIndex = this._ProfileCmb.SelectedIndex ;
			if (profileIndex < 0)
			{
				Dialog.ShowWarning(MessageInfo.Get("Není vybrán profil databáze."));
				return;
			}

			string login = this._LoginText.Text;
			string password = this._PasswText.Text;
			ConnectProfile dbProfile = this._DbProfileList[profileIndex];
			string errMessage;
			Noris.Schedule.Support.DataFace.NorisUserCls user;
			if (Steward.TryLogin(login, password, dbProfile, out errMessage, out user))
			{
				Steward.LastLogin = this._LoginText.Text;

				this._LoggedUser = user;
				this._LoggedDbProfile = dbProfile;
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
			else
				Dialog.ShowWarning(errMessage);
		}
		/// <summary>
		/// Exit button click
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void _ExitBtn_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}
		/// <summary>
		/// Uživatel, který je úspěšně přihlášen
		/// </summary>
		public NorisUserCls LoggedUser
		{
			get { return this._LoggedUser; }
		}
		private NorisUserCls _LoggedUser;
		/// <summary>
		/// DB profil, který je v logovacím okně vybrán
		/// </summary>
		public ConnectProfile LoggedDbProfile
		{
			get { return this._LoggedDbProfile; }
		}
		private ConnectProfile _LoggedDbProfile;
	}
}
